<template>
    <div id="auth-page">
      <h1>{{ isLogin ? "登录" : "注册" }}</h1>
      <form @submit.prevent="submitForm">
        <div>
          <label for="username">用户名：</label>
          <input type="text" id="username" v-model="username" required />
        </div>
        <div>
          <label for="password">密码：</label>
          <input type="password" id="password" v-model="password" required />
        </div>
        <div v-if="!isLogin">
          <label for="confirm-password">确认密码：</label>
          <input
            type="password"
            id="confirm-password"
            v-model="confirmPassword"
            required
          />
        </div>
        <button type="submit">{{ isLogin ? "登录" : "注册" }}</button>
      </form>
      <div>
        <p v-show="isLogin">
          没有账户？
          <a href="#" @click.prevent="toggleForm">立即注册</a>
        </p>
        <p v-show="!isLogin">
          已有账户？
          <a href="#" @click.prevent="toggleForm">立即登录</a>
        </p>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref } from "vue";
  import { useRouter } from "vue-router";
  import request from "../../api/request";
  
  const router = useRouter();
  const username = ref("");
  const password = ref("");
  const confirmPassword = ref("");
  const isLogin = ref(true);
  
  async function submitForm() {
    if (!isLogin.value && password.value !== confirmPassword.value) {
      alert("两次输入的密码不一致，请重新输入");
      return;
    }
  
    const url = isLogin.value ? "login" : "register";
    const data = {
      username: username.value,
      password: password.value,
    };
  
    try {
      const response = await request.post(url, data);
      // console.log(response.data.status)
      if (response.data.status === "success") {
        localStorage.setItem("username", username.value);
        // console.log(username.value);
        // router.push('/');
        router.go(0)   //刷新当前页面
      } else {
        alert(response.data.message);
      }
    } catch (error) {
      console.error("请求错误：", error);
      alert("操作失败，请重试。");
    }
  }
  
  function toggleForm() {
    isLogin.value = !isLogin.value;
  }
  </script>
  
  <style scoped>
  #auth-page {
    width: 100%;
    max-width: 400px;
    margin: 0 auto;
    padding: 20px;
    box-sizing: border-box;
  }
  
  form {
    display: flex;
    flex-direction: column;
  }
  
  div {
    margin-bottom: 1rem;
  }
  
  label {
    display: block;
    margin-bottom: 0.5rem;
  }
  
  input {
    width: 100%;
    padding: 0.5rem;
    box-sizing: border-box;
  }
  
  button {
    background-color: #4caf50;
    color: white;
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 1rem;
    /* font-weight: */
    font-weight: bold;
}

button:hover {
  background-color: #45a049;
}

a {
  color: #4caf50;
  cursor: pointer;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}
</style>